package com.abou.security.auth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.abou.mvc.controller.ControllerUtils;
import com.abou.mvc.controller.admin.HomeController;
import com.abou.mvc.controller.admin.LoginController;

/**
 * Strategy used to handle a successful user authentication
 * 
 * @author khalid
 */
public class AbouAuthenticationSuccessHandler implements
    AuthenticationSuccessHandler {
  
  /**
   * The default constructor
   */
  public AbouAuthenticationSuccessHandler() {

    super();
  }
  
  /**
   * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse,
   *      org.springframework.security.core.Authentication)
   */
  public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {

    // getting the list of role names
    Collection<GrantedAuthority> roles = authentication.getAuthorities();
    List<String> roleNames = new ArrayList<String>();
    
    for (GrantedAuthority grantedAuthority : roles) {
      
      roleNames.add(grantedAuthority.getAuthority());
    }
    
    // getting the URL to which the redirect action must be done
    String redirect = null;
    
    if (roleNames.contains(AbouAuthenticationProvider.ADMIN_ROLE)) {
      
      // the user authenticated
      redirect = HomeController.VIEW_NAME;
      
    } else {
      
      // the user is not authenticated at all
      redirect = LoginController.LOGIN_VIEW;
    }
    
    redirect =
        request.getContextPath() + ControllerUtils.VIEW_PATH_SEP + redirect
            + ControllerUtils.VIEW_NAME_SUFFIX;
    
    // redirecting
    response.sendRedirect(response.encodeRedirectURL(redirect));
  }
}
